import { useEffect } from "react";
import tocbot from "tocbot";
import debounce from "lodash/debounce";
// 暂时将样式迁移至全局
import Styles from "./styles.module.scss";

let topList: number[] = [];
let staticBorder: HTMLDivElement

interface NavCardProps {
  handleClose?: () => void
}

const initToc = (handleClose?: () => void) => {
  if (!staticBorder) {
    staticBorder = document.createElement("div");
    staticBorder.className = "-z-10 absolute top-0 left-0 border-l-4 h-full border-[#191818]";
  }

  topList = []

  let t = 0;
  const navContent = document.querySelector("#flag");
  const ele = document.createElement("div");
  ele.className = `absolute top-0 ${Styles.nav_active}`

  const content: NodeListOf<HTMLDivElement> = document.querySelectorAll(".markdown-body h2,.markdown-body h3")

  if (!content.length) {
    tocbot.destroy()
    if (navContent) navContent.innerHTML = `<div class="m-4 text-center">¯\\_(ツ)_/¯</div>`
    return
  }

  for (let i = 0; i < content.length; i++) {
    topList.push(content[i].offsetTop);

  }

  tocbot.init({
    tocSelector: '#flag',
    contentSelector: '.markdown-body',
    headingSelector: 'h1, h2, h3',
    scrollSmoothOffset: -60,
    headingsOffset: 60,
    hasInnerContainers: true,
    listClass: Styles.toc_list,
    listItemClass: Styles.toc_list_item,
    linkClass: Styles.toc_list_link,
    disableTocScrollSync: true,
    throttleTimeout: 300,
    onClick: () => {
      window.innerWidth < 892 && handleClose && handleClose()
    },
    scrollEndCallback: function (e) {
      if (navContent && navContent.scrollHeight > navContent.clientHeight) {
        navContent.scrollTop = t > 329 ? t - 300 : navContent.scrollTop;
        if (navContent.scrollTop > t) {
          navContent.scrollTop = t;
        }
      }
    }
  })

  navContent?.append(ele);
  navContent?.firstElementChild?.appendChild(staticBorder)

  const toChange = () => {
    for (let i = 0; i < topList.length; i++) {
      if (topList[i] < window.scrollY) {
        t = 30 * i;
      }
      else if (window.scrollY < topList[0] + 20) {
        t = 0;
      }
    }
    ele.style.top = `${t}px`;
  }
  document.addEventListener("scroll", debounce(toChange, 100));
  toChange()
}

const NavCardCore: React.FC<NavCardProps> = ({ handleClose }) => {
  useEffect(() => {
    document.addEventListener("astro:page-load", () => {
      requestAnimationFrame(() => {
        initToc(handleClose)
      })
    })
    initToc(handleClose)
  }, [])

  return (
    <div className="relative max-h-[330px] overflow-y-auto overflow-x-hidden scrollbar_none scroll-smooth" id="flag">
    </div>
  )
}

export default NavCardCore